package com.zyfdroid.backupftpserver.ftplets;

import org.apache.ftpserver.ftplet.Authentication;
import org.apache.ftpserver.ftplet.AuthenticationFailedException;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.impl.ConcurrentLoginPermission;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.util.ArrayList;
import java.util.List;

public class AnonymousUserManager implements UserManager {

    @Override
    public User getUserByName(String s) throws FtpException {
        if(s.toLowerCase().equals("anonymous")){
            return new AnonymousUser();
        }
        throw new FtpException("No such user. Try anonymous");
    }

    @Override
    public String[] getAllUserNames() throws FtpException {
        return new String[]{"anonymous"};
    }

    @Override
    public void delete(String s) throws FtpException {
        throw new FtpException("Read only user manager");
    }

    @Override
    public void save(User user) throws FtpException {
        throw new FtpException("Read only user manager");
    }

    @Override
    public boolean doesExist(String s) throws FtpException {
        return s.toLowerCase().equals("anonymous");
    }

    @Override
    public User authenticate(Authentication authentication) throws AuthenticationFailedException {
        return new AnonymousUser();
    }

    @Override
    public String getAdminName() throws FtpException {
        return "anonymous";
    }

    @Override
    public boolean isAdmin(String s) throws FtpException {
        return s.toLowerCase().equals("anonymous");
    }
}

class AnonymousUser implements User{

    @Override
    public String getName() {
        return "anonymous";
    }

    @Override
    public String getPassword() {
        return "";
    }

    @Override
    public List<? extends Authority> getAuthorities() {
        return new ArrayList<Authority>(){{add(new WritePermission());add(new ConcurrentLoginPermission(99,32));}};
    }

    @Override
    public List<? extends Authority> getAuthorities(Class<? extends Authority> aClass) {
        return new ArrayList<Authority>(){{add(new WritePermission());}};
    }

    @Override
    public AuthorizationRequest authorize(AuthorizationRequest authorizationRequest) {
        return authorizationRequest;
    }

    @Override
    public int getMaxIdleTime() {
        return 60000*5;
    }

    @Override
    public boolean getEnabled() {
        return true;
    }

    @Override
    public String getHomeDirectory() {
        return "/";
    }
}